package cl.foursoft.eee.actionscript.util
{
	
	import flash.display.InteractiveObject;
	import flash.display.Shape;
	import flash.display.Stage;
	import flash.events.MouseEvent;
	import flash.external.ExternalInterface;
	import flash.geom.Point;
	
	import mx.core.FlexGlobals;
	import mx.core.UIComponent;
	import mx.events.FlexEvent;
	
	public class MouseWheelSupport {
		
		//--------------------------------------
		//   Constructor 
		//--------------------------------------
		
		public function MouseWheelSupport() {
			FlexGlobals.topLevelApplication.addEventListener(FlexEvent.APPLICATION_COMPLETE, attachMouseWheelHandler);
		}
		
		//------------------------------------------------------------------------------
		//
		//   Functions  
		//
		//------------------------------------------------------------------------------
		
		//--------------------------------------
		//   Private 
		//--------------------------------------
		
		private function attachMouseWheelHandler(event : FlexEvent) : void {
			ExternalInterface.addCallback("handleWheel", handleWheel);
		}
		
		private function handleWheel(event : Object) : void {
			var obj : InteractiveObject = null;
			var applicationStage : Stage = FlexGlobals.topLevelApplication.stage as Stage;
			var mousePoint : Point = new Point(applicationStage.mouseX, applicationStage.mouseY);
			
			mousePoint = FlexGlobals.topLevelApplication.contentToGlobal(mousePoint);
			
			var objects : Array = applicationStage.getObjectsUnderPoint(mousePoint);
			
			for (var i : int = objects.length - 1; i >= 0; i--) {
				if (objects[i] is InteractiveObject) {
					obj = objects[i] as InteractiveObject;
					break;
				}
				else {
					if (objects[i] is Shape && (objects[i] as Shape).parent) {
						obj = (objects[i] as Shape).parent;
						break;
					}
				}
			}
			
			if (obj) {
				var mEvent : MouseEvent = new MouseEvent(MouseEvent.MOUSE_WHEEL, true, false,
					mousePoint.x, mousePoint.y, obj,
					event.ctrlKey, event.altKey, event.shiftKey,
					false, Number(event.delta));
					obj.dispatchEvent(mEvent);
			}
		}
	}
}